﻿import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
// 引入权限管理的路由
import management from './management.js'
// 引入元数据相关的路由
import metaData from './metaData.js'
// 引入资源管理相关的路由---包括动态功能、动态表单、元数据表单
import resource from './resource.js'
// 引入流程管理的路由---包括应用管理、流程管理、流程查看
import workflow from './workflow.js'

Vue.use(Router)

const myRouter = new Router({
  routes: [
    {
      path: '/',
      component: resolve => require(['@/views/login/Login.vue'], resolve)
    },
    {
      path: '/webLogin',
      component: resolve => require(['@/views/login/WebLogin.vue'], resolve),
      meta: {
        requiresAuth: false,
        title: '官网统一登录中转页面'
      }
    },
    {
      path: '/dashboard',
      component: resolve => require(['@/views/dashboard/Dashboard.vue'], resolve),
      meta: {
        requiresAuth: true
      },
      children: [...management, ...metaData, ...resource, ...workflow]
    },
    {
      path: '*',
      redirect: '/'
    }
  ],
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})
const routerPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}
myRouter.beforeEach((to, from, next) => {
  store.dispatch('changRouteLoading', true)
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (sessionStorage.getItem('token')) {
      // 判断当前菜单是否在功能列表中
      let hadMenuList = false
      // 通过所有的功能菜单,判断即将跳转的菜单是否在menu中
      if (sessionStorage.getItem('routerNavList') && sessionStorage.getItem('routerNavList') !== 'undefined') {
        let allMenuList = JSON.parse(sessionStorage.getItem('routerNavList'))
        for (let i = 0; i < allMenuList.length; i++) {
          if (allMenuList[i].function_url === to.fullPath) {
            hadMenuList = true
            break
          }
        }
      }
      if (from.fullPath !== '/') {
        sessionStorage.setItem('prevRoute', from.fullPath)
      }
      let payload = {
        currentRoute: hadMenuList ? to.fullPath : sessionStorage.getItem('prevRoute')
      }
      store.dispatch('changeCurrentRoute', payload)
      next()
    } else {
      next({
        path: '/',
        query: {redirect: to.fullPath}
      })
    }
  } else {
    next()
  }
})
myRouter.afterEach((to, from) => {
  store.dispatch('changRouteLoading', false)
})
export default myRouter
